package com.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.mapper.EmpiAlgorithmConfigMapper;
import com.base.service.EmpiAlgorithmConfigService;
import com.base.service.EmpiWeightConfigService;
import com.base.service.EmpiWeightFileCombinationService;
import com.base.vo.EmpiAlgorithmConfig;
import com.base.vo.EmpiWeightFileCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class EmpiAlgorithmConfigServiceImpl extends ServiceImpl<EmpiAlgorithmConfigMapper, EmpiAlgorithmConfig>
        implements EmpiAlgorithmConfigService {

    @Autowired
    EmpiWeightFileCombinationService EmpiWeightFileCombinationService;

    @Autowired
    EmpiWeightConfigService EmpiWeightConfigService;


    @Override
    @Transactional
    public boolean saveOrUpdate(EmpiAlgorithmConfig entity) {
        super.saveOrUpdate(entity);
        Integer weightConfigId = entity.getWeightConfigId();
        modifyWeightFileCombination(weightConfigId);
        return true;
    }

    /**
     * 更新满足权重的字段组合列表
     * @param weightId
     */
    private void modifyWeightFileCombination(Integer weightId) {
        QueryWrapper<EmpiWeightFileCombination> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("weight_id", weightId);
        EmpiWeightFileCombinationService.remove(queryWrapper);

        List<List<EmpiAlgorithmConfig>> list2 = EmpiWeightConfigService.listByWeight(weightId);

        List<EmpiWeightFileCombination> fileCombinationList = new ArrayList<>();
        for (List<EmpiAlgorithmConfig> empiAlgorithmConfigs : list2) {
            EmpiWeightFileCombination EmpiWeightFileCombination = new EmpiWeightFileCombination();
            int weight = 0;
            List<String> fileCombination = new ArrayList<>();
            List<String> fileNameCombination = new ArrayList<>();
            for (EmpiAlgorithmConfig empiAlgorithmConfig1 : empiAlgorithmConfigs) {
                weight += empiAlgorithmConfig1.getWeight();
                fileCombination.add(empiAlgorithmConfig1.getFields());
                fileNameCombination.add(empiAlgorithmConfig1.getFieldsName());
            }
            EmpiWeightFileCombination.setWeightId(weightId);
            EmpiWeightFileCombination.setWeight(weight);
            EmpiWeightFileCombination.setFileCombination(String.join(",", fileCombination));
            EmpiWeightFileCombination.setFileNameCombination(String.join(",", fileNameCombination));
            fileCombinationList.add(EmpiWeightFileCombination);
        }
        if (!fileCombinationList.isEmpty()) {
            EmpiWeightFileCombinationService.saveBatch(fileCombinationList);
        }
    }

}




